import Toast from 'tdesign-miniprogram/toast/index';
import { SettleDetail, CommitOrder } from '../../../services/order/orderConfirm';
import { getAddressPromise } from '../../usercenter/address/list/util';
import { getInvoicePromise } from '../receipt/util';

const stripeImg = `https://file.ydc360.com/common/ygzc/order-stripe.png`;

Page({
  data: {
    settleDetailData: {}, // 结算页详情
    orderCardList: [], // 仅用于商品卡片展示
    userAddress: null,   // 地址
    invoiceData: null,   // 发票
    accountRemark: '',   // 备注
    stripeImg,
    loading: false,
  },

  onLoad() {
    this.handleOptionsParams();
  },

  /* 结算页信息 */
  handleOptionsParams() {
    this.setData({ loading: true, });
    const goodsRequestListJson = wx.getStorageSync('order.goodsRequestList');
    const goodsCatInfoList = JSON.parse(goodsRequestListJson);
    SettleDetail({ goodsCatInfoList }).then(res => {
      this.setData({ loading: false });
      if (res.code == '0000') {
        let settleDetailData = { totalGoodsCount: 0, totalPayAmount: 0, settleType: 1 };
        let invoiceData = null;
        res.data.goodsInfoList.forEach(item => {
          settleDetailData.totalGoodsCount += Number(item.num)
          settleDetailData.totalPayAmount += Number(item.goodsAmount)
        });
        if (res.data.invoiceTitle) invoiceData = { invoiceType: res.data.invoiceType, invoiceTitle: res.data.invoiceTitle }
        this.setData({ orderCardList: res.data.goodsInfoList, userAddress: res.data, settleDetailData, invoiceData })
      }
    });
  },

  /* 选择地址 */
  onGotoAddress() {
    getAddressPromise().then((address) => {
      address.addressId = address.id;
      this.setData({ userAddress: address })
    })
    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=true&isOrderSure=1${this.data.userAddress.addressId}`,
    });
  },

  /* 订单备注 */
  onNotes() {
    const { accountRemark } = this.data.settleDetailData
    this.setData({ dialogShow: true, accountRemark: accountRemark ? accountRemark : '' });
  },
  // 监听备注表单
  onInput(e) {
    this.setData({ 'accountRemark': e.detail.value })
  },
  /* 备注确认 */
  onNoteConfirm() {
    this.setData({
      dialogShow: false,
      'settleDetailData.accountRemark': this.data.accountRemark
    });
  },
  /* 备注取消 */
  onNoteCancel() {
    this.setData({
      dialogShow: false,
    });
  },

  // 提交订单
  submitOrder() {
    const { orderCardList, userAddress, settleDetailData, invoiceData } = this.data;
    if (!userAddress) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请添加收货地址',
        duration: 1000,
        icon: 'help-circle',
      });
      return;
    }
    if (!invoiceData) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请添加发票抬头',
        duration: 1000,
        icon: 'help-circle',
      });
      return;
    }
    const params = { orderGoodsList: [], addressId: userAddress.addressId, orderAmount: settleDetailData.totalPayAmount, accountRemark: settleDetailData.accountRemark, invoiceType: invoiceData.invoiceType, invoiceTitle: invoiceData.invoiceTitle };
    orderCardList.forEach(item => {
      params.orderGoodsList.push({ goodsAmount: item.goodsAmount, goodsId: item.goodsId, goodsNum: item.num, price: item.price, })
    });
    CommitOrder(params).then(res => {
      if (res.code == '0000') {
        wx.redirectTo({ url: `/pages/order/pay-result/index` });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: res.msg || '提交订单超时，请稍后重试',
          duration: 1000,
          icon: '',
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      }
    });
  },
  // 跳转 开发票
  onReceipt() {
    getInvoicePromise().then((invoice) => {
      this.setData({ invoiceData: invoice })
    })
    wx.navigateTo({
      url: `/pages/order/receipt/index?selectMode=true`,
    });
  },
});
